//
//  BK_StoreOrder_VC.m
//  bestkeep
//
//  Created by TOPTEAM on 2017/3/31.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BK_StoreOrder_VC.h"
#import "BK_StoreOrderDetail_VC.h"
#import "BK_StoreOrder_Cell.h"
#import "BKMyAction.h"

#import "BK_StorePay_VC.h"
#import "BK_SP_Success_VC.h"
#import "BK_SP_Fail_VC.h"

#import "BK_OD_Tool.h"
#import "BK_StoreOrder_Model.h"
#import <Masonry.h>
@interface BK_StoreOrder_VC ()
<
UITableViewDelegate,
UITableViewDataSource
>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)ExceptionView *exceptionView;
@property(nonatomic, strong)NSMutableArray*marr_Section;
@property(nonatomic, assign)NSInteger      pageNo;
@property(nonatomic, strong)NSMutableArray*marr_Data;
@end

@implementation BK_StoreOrder_VC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self  setProperty];
    [self  createUI];
    [self  setUpRefresh];
    [self  check_NetWork];
    [BKMyAction writeUTOUUOrderStatus];
}
#pragma mark==================setProperty======================
-(void)setProperty{
    _pageNo=1;
    _marr_Data=[[NSMutableArray alloc]init];
    self.view .backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"小店订单";
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    _marr_Section=[[NSMutableArray alloc]init];
    
}

#pragma mark==================createUI======================
-(void)createUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
    }];
    
}
#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            /*
             * 获取小店订单数据
             */
            [self Get_BK_StoreOrder_Data];
        }
            break;
        default: {
            [HUD dismiss];
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
            break;
    }
}
/*
 * 获取小店订单数据
 */
-(void)Get_BK_StoreOrder_Data{
    
    if ([RequestManager reachabilityStatus] == RequestReachabilityStatusUnknown || [RequestManager reachabilityStatus] == RequestReachabilityStatusNotReachable) {
        kOrderPromptMsg(@"请检查您的网络");
        return;
    }
    
    if (self.exceptionView) {//先消失,防止重复;
        [self.exceptionView dismiss];
        self.exceptionView = nil;
    }
        
    NSString *const BKStoreOrderListPage_URL      = @"store/orderListPage";
    
    NSDictionary *paramDic =  @{@"pageNo" : [NSString stringWithFormat:@"%ld",(long)_pageNo],@"pageSize" : @"20"};
    [BKIndicationView showInView:self.view];
    [[RequestManager manager] bkDataRequest:RequestMethodGet URLString:kOrderURL(BKStoreOrderListPage_URL) parameters:paramDic success:^(id  _Nullable responseObject){
        [BKIndicationView dismiss];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        BOOL success = [responseObject[@"success"] boolValue];
        if (!success) {
            if (_pageNo==1) {
                /*
                 * 请求失败
                 */
                self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
                ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
                    [self.exceptionView dismiss];
                    self.exceptionView = nil;
                    [self Get_BK_StoreOrder_Data];
                }];
                [self.exceptionView addAction:action];
                [self.exceptionView showInView:self.view];
            }else{
                kOrderPromptMsg(responseObject[@"msg"]);
                _pageNo--;
            }
            
        }else{
            if(responseObject[@"data"]){
                NSDictionary * dic=responseObject[@"data"];
                NSArray * arr=dic[@"items"];
                if (arr.count>0) {
                    
                    [_marr_Data addObjectsFromArray:arr];
                    if (_marr_Data.count%20==0) {
                        self.tableView.mj_footer.hidden = NO;
                    }else{
                       self.tableView.mj_footer.hidden = YES;
                    }
                    [self Create_Marr_Section];
                    
                }else{
                    if (_pageNo==1) {
                        /*
                         * 无数据
                         */
                        self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoData];
                        self.exceptionView.contentLabel.text = @"";
                        self.exceptionView.contentLabel.hidden=YES;
                        ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoData handler:^(ExceptionViewAction *action) {
                            [self.exceptionView dismiss];
                            self.exceptionView = nil;
                            [self Get_BK_StoreOrder_Data];
                        }];
                        [self.exceptionView addAction:action];
                        [self.exceptionView showInView:self.view];
                    }else{
                        /*
                         * 数据加载完成
                         */
                        self.tableView.mj_footer.hidden = YES;
                    }
                }
            }
        }
        
    }failure:^(id  _Nullable responseObject, NSError * _Nullable error){
        
        if (_pageNo==1) {
            [BKIndicationView dismiss];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            ExceptionCodeType errorType = ExceptionCodeTypeRequestFailed;
            if (error.code == -1009) {
                errorType = ExceptionCodeTypeNoNetwork;
            }else if (error.code == -1001){
                errorType = ExceptionCodeTypeRequestFailed;
            }else if (error.code == 502 || error.code == 404){
                errorType = ExceptionCodeTypeServerError;
            }else{
                errorType = ExceptionCodeTypeFailedToLoad;
            }
            self.exceptionView = [ExceptionView exceptionViewWithType:errorType];
            ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:errorType handler:^(ExceptionViewAction *action) {
                [self Get_BK_StoreOrder_Data];
            }];
            [self.exceptionView addAction:retryAction];
            [self.exceptionView showInView:self.view];
        }else{
            _pageNo--;
            NSString *errorMsg;
            if (error.code == -1001) {
                errorMsg = @"请求超时";
            }else if(error.code == 502){
                errorMsg = @"服务器开小差了，请稍后再试！";
            }else{
                errorMsg = @"请求失败";
            }
            kOrderPromptMsg(errorMsg);
        }
    }];
}

#pragma mark  设置刷新
-(void)setUpRefresh{
    BKRefreshGifHeader *headerRefresh = [BKRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(BK_Order_Update_Header)];
    self.tableView.mj_header = headerRefresh;
    BKMyOrderFooterAutoReferesh *footer = [BKMyOrderFooterAutoReferesh footerWithRefreshingTarget:self refreshingAction:@selector(BK_Order_Refresh_Footer)];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}

-(void)BK_Order_Update_Header{
    _pageNo=1;
    [_marr_Data removeAllObjects];
    [self Get_BK_StoreOrder_Data];
}

-(void)BK_Order_Refresh_Footer{
    _pageNo++;
    [self Get_BK_StoreOrder_Data];
}

-(void)Create_Marr_Section{

    [_marr_Section removeAllObjects];
    
    NSMutableArray * marr_Cells=[[NSMutableArray alloc]init];

    for(int i=0 ;i<_marr_Data.count; i++){
        CellModel* model =[[CellModel alloc]init];
        model.reuseIdentifier = NSStringFromClass([BK_StoreOrder_Cell class]);
        model.className=NSStringFromClass([BK_StoreOrder_Cell class]);
        model.height = [BK_StoreOrder_Cell computeHeight:nil];
        model.selectionStyle=UITableViewCellSelectionStyleNone;
        model.accessoryType=UITableViewCellAccessoryNone;
        
        /*
         * 传递参数
         */
        BK_StoreOrder_Model * model_SO = [BK_StoreOrder_Model  mj_objectWithKeyValues:_marr_Data[i]];
        model.userInfo = model_SO;
        
        [marr_Cells addObject:model];
    }
    SectionModel *model0=[SectionModel sectionModelWithTitle:@"" cells:marr_Cells];
    model0.headerhHeight=0.0001;
    model0.footerHeight=0.0001;
    [_marr_Section addObject:model0];
    
    [_tableView reloadData];
    
    
}


#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.footerHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    return cm.height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = cm.selectionStyle;
    
    if ([cm.className isEqualToString:NSStringFromClass([BK_StoreOrder_Cell class])]) {
        BK_StoreOrder_Cell *ex_cell=(BK_StoreOrder_Cell *)cell;
        
        [ex_cell relayOutUIWithModel:cm.userInfo];
        
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    BK_StoreOrderDetail_VC * vc = [[BK_StoreOrderDetail_VC alloc]init];
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    BK_StoreOrder_Model *model=cm.userInfo;
    vc.order_no=model.order_no;
    if (model.order_no) {
        [self.navigationController pushViewController:vc animated:YES];

    }
    
//    BK_SP_Success_VC * vc = [[BK_SP_Success_VC alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
//    

//    BK_SP_Fail_VC * vc = [[BK_SP_Fail_VC alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
    
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
